<?php

/**
 * Manage_product_categoriesController - Controller dùng để quản lý category tin tức
 * 
 * @author huytbt
 * @date 2011-06-30
 * @version 1.0
 */
class Manage_product_categoriesController extends Controller
{
		//public $backend_left_menu = "_left_menu";
		public $backend_left_menu = "application.modules.products.views.admin_menu._left_menu";
		public $backend_left_menu_datas = array('list'	=>	array());
		//public $backend_left_menu_datas = false;
		private $_model;
		public $layout='//layouts/main';
		public $pageTitle = "Manage product categories";
		public function init()
		{
				Yii::app()->theme = 'backend';
				parent::init();
		}

    /**
     * @todo Kiểm tra quyền
     */
    
    /**
     * @return string Trả về các action (cách nhau bằng dấu phẩy) cho phép truy cập mà không cần xác thực quyền
    public function allowedActions() {
        return '*';
    }
     */
    
    public function actionView($id)
    {
		$this->pageTitle = 'View a category';
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
	}
	
    public function actionCreate()
    {
		$this->pageTitle = 'Create a category';
        $model = new ProductCategories;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        if (isset($_POST['ProductCategories'])) {
            $model->attributes = $_POST['ProductCategories'];
            $fileUpload = CUploadedFile::getInstance($model, 'image');
            if (isset($fileUpload)) {
                $uploadPath = YiiBase::getPathOfAlias('webroot') .$this->module->catalogImg['url'];//'/wwwroot/upload_files/product_categories/';
                if (!is_dir($uploadPath))
                    mkdir($uploadPath);
                $filename = $model->alias . '.' . $fileUpload->getExtensionName(); //time() . mt_rand(0, 0xfff) . '.' . $fileUpload->getExtensionName();
                $fileUpload->saveAs($uploadPath . $filename);
                $model->image = $filename;
            }
            
            if ($model->save()) {
                $this->redirect(array('admin'));
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id)
    {
		$this->pageTitle = 'Create a category';
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['ProductCategories'])) {
            $model->attributes = $_POST['ProductCategories'];
            
            // Upload image
            $fileUpload = CUploadedFile::getInstance($model, 'image');
            if (isset($fileUpload)) {
            	$uploadPath = YiiBase::getPathOfAlias('webroot').$this->module->catalogImg['url'];
                
                // Delete old image
                if ($model->image) {
                	if(is_file($uploadPath . '/' . $model->image)){
                    	unlink($uploadPath . '/' . $model->image);
                	}
                }
                
                if (!is_dir($uploadPath))
                    mkdir($uploadPath);
                
                $filename = $model->alias . '.' . $fileUpload->getExtensionName(); //time() . mt_rand(0, 0xfff) . '.' . $fileUpload->getExtensionName();
                $fileUpload->saveAs($uploadPath . '/' . $filename);
                $model->image = $filename;
            }
            
            if ($model->save())
                $this->redirect(array('admin'));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
       	if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $model = $this->loadModel($id);
            if ($model->image) {
                $uploadPath = YiiBase::getPathOfAlias('webroot').$this->module->catalogImg['url'];
                if(is_file($uploadPath . '/' . $model->image))
                	unlink($uploadPath . '/' . $model->image);
            }
            // delete all product
            $productMiddles = ProductMiddle::model()->findAll('category_id=:catId',array(':catId'=>$id));
            foreach ($productMiddles as $productMiddle){
            	$rs = Products::model()->deleteByPk($productMiddle->product_id);
            	$productMiddle->delete();
            }
            $model->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            //if (!isset($_GET['ajax']))
                //$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
      	}
      	else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        $model = new ProductCategories('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['ProductCategories']))
            $model->attributes = $_GET['ProductCategories'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id)
    {
        $model = ProductCategories::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'product-categories-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
